package com.example.DemoDataeaseExample.util;

import java.sql.*;

public class JdbcUtils {

    // 关闭资源
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 打印查询结果
    public static void printResults(ResultSet rs) throws SQLException {
        if (rs == null) {
            System.out.println("结果集为空");
            return;
        }

        // 获取结果集元数据
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();

        // 打印表头
        for (int i = 1; i <= columnCount; i++) {
            System.out.print(metaData.getColumnName(i) + "\t");
        }
        System.out.println();

        // 打印分隔线
        System.out.println("--------------------------------------------------");

        // 打印数据
        int rowCount = 0;
        while (rs.next()) {
            rowCount++;
            for (int i = 1; i <= columnCount; i++) {
                Object value = rs.getObject(i);
                System.out.print((value != null ? value.toString() : "NULL") + "\t");
            }
            System.out.println();
        }

        if (rowCount == 0) {
            System.out.println("没有数据");
        }

        System.out.println();
    }
}